﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Threading;
using SqlServerAdmin;
using IQ.BaseWindows;
using IQ.DbBase;

namespace IQ.DbA
{
    public partial class FrmMaintenance : Form
    {
        #region # Constructor #
        public FrmMaintenance()
        {
            InitializeComponent();
            General.LoadFormColor(frmDir);
        }
		#endregion
		
		#region - Private variables - 
        private enum MaintenaceCmd
        {
            Backup, Restore
        }
        private FrmServerDir frmDir = new FrmServerDir();
        private int databaseId = 0;
        private string connectionString;
        private SqlCommand cmdProgress;
        //
        private string cmdDd;
        private string cmdPath;
        #endregion 

		#region - Private methods - 
        private void loadDatabases()
        {
            DataTable datQry = DbHelper.Load_Table(SqlQueries.SqlDataBases);
            this.cbxDBs.Items.Clear();
            for (int i = 0; i < datQry.Rows.Count; i++)
            {
                this.cbxDBs.Items.Add(datQry.Rows[i][0].ToString());
            }
            //cbxDBs.SelectedIndex = cbxDBs.Items.IndexOf(ConnectionDB.Database);
        }

        private void loadActiveUsers()
        {
            DataTable datQry = DbHelper.Load_Table(SqlQueries.SqlActiveConnections);
            grdData.DataSource = datQry;
            General.SetGridViewColumnsTo(grdData, SqlConst.viewActiveUsers);
        }

        private void setDatabaseId(string name)
        {
            databaseId = DbHelper.ExecuteSql_rInt(SqlQueries.GetSqlDatabaseId(name), 0);
        }

        private int getPercentComplete()
        {
            try
            {
                if (cmdProgress.Connection.State != ConnectionState.Open)
                    cmdProgress.Connection.Open();
                cmdProgress.CommandText = SqlQueries.GetSqlPercentComplete(databaseId);
                return Convert.ToInt32(cmdProgress.ExecuteScalar());
            }
            catch// (Exception e)
            {
                //throw e;
                return 0;
            }
            //return DbHelper.ExecuteSql_rInt(SqlQueries.GetSqlPercentComplete(databaseId), 0);            
        }

        private void setServerItem()
        {
            frmDir.ShowDialog();
            txtFileName.Text = frmDir.SelectedFile;
        }

        private void execServerCommand(MaintenaceCmd cmd)
        {
            txtRes.Text = "";
            Stopwatch stopWatch = new Stopwatch();
            cmdDd = cbxDBs.Text;
            cmdPath = txtFileName.Text;
            setDatabaseId(cbxDBs.Text);
            if (databaseId != 0)
            {
                pgProg.Visible = true;
                foreach (Control c in this.Parent.Parent.Controls)
                    c.Enabled = false;
                pgProg.Enabled = true;
                tmrProgress.Enabled = true;
                stopWatch.Start();
                Thread th = null;
                if (cmd == MaintenaceCmd.Restore)
                {
                    th = new Thread(new ThreadStart(restoreDb));
                }
                else
                {
                    th = new Thread(new ThreadStart(backupDb));
                }
                th.Start();
                while (th.IsAlive)
                {
                    Application.DoEvents();
                }
                pgProg.Value = pgProg.Maximum;
                tmrProgress.Enabled = false;
                foreach (Control c in this.Parent.Parent.Controls)
                    c.Enabled = true;
                //
                stopWatch.Stop();
                // Get the elapsed time as a TimeSpan value.
                TimeSpan ts = stopWatch.Elapsed;
                txtRes.AppendText("Time to run job : " + ts.ToString() + System.Environment.NewLine);
                pgProg.Visible = false;
            }
            else
                General.MesDlg("Database not found.", 'E');
        }

        private void backupDb()
        {
            SqlMaintenance.BackupDb(cmdPath, cmdDd);
        }
        private void restoreDb()
        {
            SqlMaintenance.RestoreDb(cmdPath, cmdDd);
        }
		#endregion 
		
        #region - Public properties / variables -
        public string ConnectionString
        {
            get { return connectionString; }
            set
            {
                connectionString = value;
                DbHelper.SetConnectionString(value);
            }
        }
        #endregion

		//#region - Public methods - 
		//#endregion
		
		#region - Bind Methods - 
		#endregion
		
		#region - Form Events -
		// This region is for event handler methods that are called without the user knowing about it.
		// Such as the page loading.
        private void FrmMaintenance_Load(object sender, EventArgs e)
        {
            loadDatabases();
            //
            SqlConnection conProgress = (SqlConnection)DbHelper.GetConnection();
            cmdProgress = conProgress.CreateCommand();
            cmdProgress.CommandType = CommandType.Text;
        }
        private void tmrProgress_Tick(object sender, EventArgs e)
        {
            pgProg.Value = getPercentComplete();
        }

		#endregion 
		
		#region - Control Methods -
		// This region is for event handler methods that are called knowingly by the user.
		// Such as a button being clicked.

        // Backup Db
        private void btnBackup_Click(object sender, EventArgs e)
        {
            bool tmpRes = (txtFileName.Text != "");
            if (tmpRes)
                tmpRes = General.MesDlg("Backup to file: " + txtFileName.Text + "?", 'C') == DialogResult.Yes;
            if (!tmpRes)
            {
                setServerItem();
                tmpRes = (txtFileName.Text != "");
            }
            if (txtFileName.Text != "")
            {
                /*
                 if (!tmpRes)
                 {
                    string tmpFN = Microsoft.VisualBasic.Interaction.InputBox("Hello", "Enter something fun", "Type something"); 
                    InputBox('Backup file','Please specify a backup file?',cbxDBs.Text+'.BAK');
                    txtServerItem.Text += "\\" + tmpFN.Trim();
                    tmpRes = tmpFN.Trim() != "";
                 }
                string tmpMsg = "";
                if (tmpRes)
                    tmpMsg = "Note: Backup will overwrite the file if it already exists.";
                */
                if (General.MesDlg("Are you sure you want to backup database " + cbxDBs.Text, 'C')
                    == DialogResult.Yes)
                {
                    execServerCommand(MaintenaceCmd.Backup);
                    // Application.DoEvents();
                    txtRes.AppendText("Backup database " + cbxDBs.Text + " completed." + Environment.NewLine);
                }
                else
                {
                    if (!tmpRes)
                        General.MesDlg("No file was selected.", 'E');
                }
            }
        }

        // Restore Db
        private void btnRestore_Click(object sender, EventArgs e)
        {
            bool tmpRes = false;
            if (txtFileName.Text != "")
                tmpRes = General.MesDlg("Restore from file: " + txtFileName.Text + "?", 'C') == DialogResult.Yes;
            if (!tmpRes)
                setServerItem();
            if (txtFileName.Text != "")
            {
                if (General.MesDlg("Are you sure you want to restore database " + cbxDBs.Text, 'C')
                    == DialogResult.Yes)
                {
                    execServerCommand(MaintenaceCmd.Restore);
                    // Application.DoEvents();
                    txtRes.AppendText("Restore database " + cbxDBs.Text + " completed." +
                        " Execute time: " + Environment.NewLine);//dtmMT.CMDtime);
                }
                else
                    General.MesDlg("No file was selected.", 'E');
            }
        }

        // Shrink Db
        private void txtShrinkP_KeyPress(object sender, KeyPressEventArgs e)
        {
            int isNumber = 0; 
            e.Handled = !int.TryParse(e.KeyChar.ToString(), out isNumber);
        }
        private void btnShrink_Click(object sender, EventArgs e)
        {
            if (General.MesDlg("Are you sure you want to shrink database:  " +
                cbxDBs.Text, 'C') == DialogResult.Yes)
            {
                SqlMaintenance.ShrinkDb(cbxDBs.Text, txtFreeP.Text);
                txtRes.AppendText("Database shrink completed, for " + cbxDBs.Text);
            }
        }

        // Drop Db
        private void btnDrop_Click(object sender, EventArgs e)
        {
            if (General.MesDlg("Drop database " + cbxDBs.Text, 'C') == DialogResult.Yes)
            {
                SqlMaintenance.DropDb(cbxDBs.Text);
                txtRes.AppendText("Database drop completed, for " + cbxDBs.Text);
            }
        }
        
        // New database
        private void btnCreate_Click(object sender, EventArgs e)
        {
            if (General.MesDlg("Are you sure you want to create the new database:  " +
                txtNewDbName.Text + " on " + txtNewDbDir.Text, 'C') == DialogResult.Yes)
            {
                SqlMaintenance.CreateDb(txtNewDbDir.Text, txtNewDbName.Text);
                txtRes.AppendText("Database create completed, for " + txtNewDbDir.Text);
                General.MesDlg("Please reconnect to this server, to be able to see the new database in the drop down list.", 'I');
            }
        }

        // Active Users
        private void btnUser_Click(object sender, EventArgs e)
        {
            loadActiveUsers();
        }
        private void btnKillGrd_Click(object sender, EventArgs e)
        {
            txtRes.Clear();
            DataTable dt = (DataTable)grdData.DataSource;
            foreach (DataRowView dr in dt.DefaultView)
            {
                SqlMaintenance.Kill(dr[0].ToString());
            }
            loadActiveUsers();
        }
        private void btnKillSel_Click(object sender, EventArgs e)
        {
            txtRes.Clear();
            foreach (DataGridViewRow dr in grdData.SelectedRows)
            {
                SqlMaintenance.Kill(dr.Cells[0].Value.ToString());
            }
            loadActiveUsers();
        }
        #endregion

    }
}
